package com.ttbj.websocket.handler;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.ttbj.controller.constant.WebSessionMap;

public abstract class DefultWebSocketHandlerAdapter extends TextWebSocketHandler {
	private static final Logger logger = LoggerFactory.getLogger(DefultWebSocketHandlerAdapter.class);
	private String USER_ID = "";

	public DefultWebSocketHandlerAdapter(String userId) {
		this.USER_ID = userId;
	}

	/* 连接成功触发此方法 */
	abstract void onopen(WebSocketSession session);

	/* 连接关闭触发此方法 */
	abstract void onclose(WebSocketSession session, CloseStatus status);

	/* 消息接收触发此方法 */
	abstract void onmessage(String userId, String message);

	/* 连接异常触发此方法 */
	abstract void onerror(WebSocketSession session, Throwable exception);

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info("成功连接");
		String userId = (String) session.getAttributes().get(USER_ID);
		logger.info("获取到用户的Id:{}", userId);
		WebSessionMap.put(userId, session);
		logger.info("当前线上用户数量：" + WebSessionMap.size());
		onopen(session);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		logger.info("连接关闭");
		String userId = (String) session.getAttributes().get(USER_ID);
		logger.info("获取到用户的Id:{}", userId);
		WebSessionMap.remove(userId);
		logger.info("剩余在线用户" + WebSessionMap.size());
		onclose(session, status);
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		logger.info("服务器收到信息:{}", message);
		String userId = (String) session.getAttributes().get(USER_ID);
		logger.info("收到消息的客户id:{}", userId);
		onmessage(userId, message.getPayload());
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		super.handleTransportError(session, exception);
		if (session.isOpen()) {
			session.close();
		}
		logger.debug("传输出现异常，关闭websocket连接");
		String userId = (String) session.getAttributes().get(USER_ID);
		WebSessionMap.remove(userId);
		onerror(session, exception);
	}

	public boolean sendMessage(String userId, TextMessage messageInfo) throws Exception {
		WebSocketSession session = WebSessionMap.get(userId);
		// 根据用户名去判断用户接收消息的用户
		if(null == session){
			return false;
		}
		try {
			if (session.isOpen()) {
				session.sendMessage(messageInfo);
				logger.info("发送消息给：" + userId + "内容：" + messageInfo);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

}
